<?php

namespace App\Dao;

use App\Model\Mission;
use App\Model\MissionConfig;
use Hyperf\Context\ApplicationContext;
use Hyperf\DbConnection\Db;
use function Hyperf\Translation\trans;

class MissionDao
{
    private static $instance;

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = Applicationcontext::getcontainer()->get(self::class);
        }
        return self::$instance;
    }


    /**
     * Note - 获取用户任务列表
     * DateTime 2024/8/9 11:29
     * User Admin
     * @param $uid
     * @param $gender
     * @return mixed[]
     */
    public function getUserMissionList($uid, $gender)
    {
        $missions = MissionConfig::query()->from('tb_mission_config as c')
            ->leftJoinSub(function ($query) use ($uid) {
                $query->select(DB::raw('count, status, max(create_time) as create_time, mission'))->from('tb_mission as a')->where('a.uid', $uid)->groupBy('a.mission');
            }, 'm', 'm.mission', '=', 'c.id')
            ->where('c.gender', $gender)
            ->select([
                'c.id',
                'c.type',
                'c.mission',
                'c.extra',
                'c.text',
                'c.total',
                'c.icon',
                'c.visible',
                'c.award_count',
                DB::raw('COALESCE(m.count, 0) as count'),
                DB::raw('COALESCE(m.status, 0) as status'),
                DB::raw('m.create_time'),
            ])
            ->orderBy('c.order_index')
            ->get();

        return $missions->toArray();

    }


    /**
     * Note -
     * DateTime 2024/8/9 11:30
     * User Admin
     * @param $uid
     * @param $sex
     * @param $language
     * @return array
     */
    public function getUserMissionInfo($uid, $sex, $language)
    {
        $time = date('Y-m-d');
        $rs = $this->getUserMissionList($uid, $sex);
        $missions = [];
        foreach ($rs as $v) {
            if ($v['type'] == 'daily' && $v['create_time'] < $time) {
                $v['count'] = $v['status'] = 0;
            }
            $id = $v['id'];
            $missions[$id] = $v;
        }
        if ($sex == 2) {
            $data = [
                'profile' => ($missions[2001]['status'] == 0)
                    ? (trans('mission.' . $missions[2001]['mission'], [], $language) . ' ' . trans('mission.金币', ['num' => $missions[2001]['award_count']], $language))
                    : '',
                'upload_video' => ($missions[2003]['status'] == 0)
                    ? (trans('mission.' . $missions[2003]['mission'], [], $language) . ' ' . trans('mission.金币' . $missions[2003]['extra'], ['num' => $missions[2003]['award_count']], $language))
                    : '',
                'upload_album' => ($missions[2004]['status'] == 0)
                    ? (trans('mission.' . $missions[2004]['mission'], [], $language) . ' ' . trans('mission.金币' . $missions[2004]['extra'], ['num' => $missions[2004]['award_count']], $language))
                    : '',
                'head_image' => '',
                'signature' => '',
                'edit' => '',
                'mission' => '',
            ];
        } else {
            $flag = false;
            foreach ($missions as $v) {
                if ($v['status'] == 1) {
                    $flag = true;
                    break;
                }
            }
            $data = [
                'profile' => ($missions[1001]['status'] == 0)
                    ? (trans('mission.' . $missions[1001]['mission'], [], $language) . ' ' . trans('mission.金币', ['num' => $missions[1001]['award_count']], $language))
                    : '',
                'upload_video' => '',
                'upload_album' => '',
                'head_image' => ($missions[1002]['status'] == 0)
                    ? (trans('mission.' . $missions[1002]['mission'], [], $language) . ' ' . trans('mission.金币', ['num' => $missions[1002]['award_count']], $language))
                    : '',
                'signature' => '',
                'edit' => ($missions[1001]['status'] == 0 || $missions[1002]['status'] == 0) ? trans('mission.金币待领取', [], $language) : '',
                'mission' => $flag ? trans('mission.金币待领取', [], $language) : '',
            ];
        }

        return $data;

    }


    /**
     * Note - 获取任务状态
     * DateTime 2024/8/14 12:03
     * User Admin
     * @param $uid
     * @param $missionId
     * @return array|null
     */
    public function getMissionStatus($uid, $missionId)
    {
        // $sql = <<<SQL
        //         SELECT m.id,m.status,UNIX_TIMESTAMP(m.create_time) create_time,c.type,c.award_type,c.award_count,c.max_award_count
        //         FROM tb_mission m
        //         LEFT JOIN tb_mission_config c ON m.mission=c.id
        //         WHERE m.uid=$uid AND m.mission=$missionId AND m.status=1
        //         ORDER by m.id DESC
        //         LIMIT 1
        // SQL;
        // $rs = $this->findOne($sql);
        $data = Mission::query()->from('tb_mission AS m')
            ->leftJoin('tb_mission_config AS c', 'm.mission', '=', 'c.id')
            ->select([
                'm.id',
                'm.status',
                DB::raw('UNIX_TIMESTAMP(m.create_time) as create_time'),
                'c.type',
                'c.award_type',
                'c.award_count',
                'c.max_award_count',
            ])
            ->where('m.uid', $uid)
            ->where('m.mission', $missionId)->where('m.status', 1)
            ->orderByDesc('m.id')->first();
        if (!$data){
            return null;
        }

        $time = strtotime(date('Y-m-d'));
        $type = $data['type'];
        $createTime = intval($data['create_time']);
        // return ($type != 'daily' || $createTime >= $time) ? [$data['id'], $data['status'], $data['award_type'], $data['award_count'], $data['max_award_count']] : null;
        if ($type != 'daily' || $createTime >= $time) {
            return [$data['id'], $data['status'], $data['award_type'], $data['award_count'], $data['max_award_count']];
        } else {
            return null;
        }
    }


    /**
     * Note - 设置任务完成状态
     * DateTime 2024/8/14 12:04
     * User Admin
     * @param $id
     * @return int
     */
    public function setMissionCompleteStatus($id)
    {
        // $time = date("Y-m-d H:i:s");
        // $sql = "UPDATE tb_mission SET status=2,update_time='$time' WHERE id=$id";
        // return $this->execute($sql);
        return Mission::query()->where('id', $id)->update(['status' => 2, 'update_time' => date("Y-m-d H:i:s")]);
    }

}